package it.univaq.di.helpdesk.common.utils;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaMailHelper {
	private static JavaMailHelper instance = null;
	
	private InternetAddress sender;
	private Session mailSession;
	private MimeMessage message;
	
	private JavaMailHelper(JavaMailSMPTData smtpData) throws MessagingException {
		this.sender = new InternetAddress(smtpData.getMailSender());
		
		Properties props = new Properties();
		props.put("mail.smtp.host", smtpData.getMailSMPTHost());
		
		if (smtpData.isAuthEnabled()) {
			props.put("mail.smtp.auth", "true");
			props.put("mail.user", smtpData.getMailUsername());
			props.put("mail.password",smtpData.getMailPassword());
		}
		
		this.mailSession = Session.getInstance(props, null);
		
		this.message = new MimeMessage(this.mailSession);
		this.message.setFrom(this.sender);
		
		this.message.setHeader("X-Mailer", "smtpsend");
		this.message.setSentDate(new Date());
	}
	
	public static synchronized void initMailer(JavaMailSMPTData smtpData) throws MessagingException {
		if (instance == null) {
			instance = new JavaMailHelper(smtpData);
		}
	}
	
	public static JavaMailHelper getInstance() {
		return instance;
	}
	
	public void sendMail(String recipient, String subject, String content) throws MessagingException {
		InternetAddress toAddress = new InternetAddress(recipient);
		
		this.message.setRecipient(Message.RecipientType.TO, toAddress);
		this.message.setSubject(subject);
		this.message.setText(content);
		
		Transport.send(this.message);
	}
}
